<?php session_start() ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Editar un fitxer</title>
	<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<div id="edit-box" class="login-box">
<?php // Script 12.2 - mysql_connect.php #2
/* This script connects to the MySQL server. */
	include('gvar.php');
	if(isset($_GET['id']) && is_numeric($_GET['id'])){

		$query= 'SELECT f.Name, f.ActivationDate,f.DateExpiry,f.Password, g.Name,s.Name,f.UserName, g.Code, s.Code FROM (Files f INNER JOIN Grade g on f.CodeGrade = g.Code) INNER JOIN Subject s on f.CodeSubject = s.Code where f.Code='.$_GET['id'];
		/*
			On mysql_fetch_array(variable, MYSQL_NUM):
			0: f.Name
			1: f.ActivationDate
			2: f.DateExpiry
			3: f.Password
			4: g.Name
			5: s.Name
			6: f.UserName
			7: g.Code
			8: s.Code
		*/
		if($r=mysql_query($query,$dbc)){
			$row=mysql_fetch_array($r, MYSQL_NUM);
					print '<form action="edit.php" method="post">
	<div>Nom: </div><input type="text" name="Name" size="40" maxsize="100" value="' . htmlentities(stripslashes($row[0]),ENT-COMPAT,"UTF-8") . '" />
	<div>Data d\'activació (AAAA-MM-DD): </div><input type="text" name="ActDate" size="40" maxsize="100" value="' . htmlentities(stripslashes($row[1]),ENT-COMPAT,"UTF-8") . '" />
	<div>Data d\'activació (AAAA-MM-DD):: </div><input type="text" name="DateExp" size="40" maxsize="100" value="' . htmlentities(stripslashes($row[2]),ENT-COMPAT,"UTF-8") . '" />
	<div>Password: </div><input type="text" name="Pass" size="40" maxsize="100" value="' . htmlentities(stripslashes($row[3]),ENT-COMPAT,"UTF-8") . '" />
		<div>Curs: <select name="Grade" class="styled-select">
						<option value="">Seleccioni un curs</option>';
							
							$gradeOptions = 'SELECT * FROM Grade'; 

							if($r = mysql_query($gradeOptions,$dbc)) {   //Creates all the possible options for the grade field
								while ($rowGrade = mysql_fetch_array($r, MYSQL_NUM)){
									echo '<option value="'.$rowGrade[1].'"'.($rowGrade[0] == $row[7] ? ' selected' : '') .'>'.$rowGrade[1].'</option>';
								}
							}
					 	
				print '</select>
	</div>
	<div>Assignatura: <select name="Subject" class="styled-select">
						<option value="">Seleccioni una assignatura</option>';
						
							$subjectOptions = 'SELECT * FROM Subject';

							if($r = mysql_query($subjectOptions,$dbc)) {    //Creates all the possible options for the subject field
								while ($rowSubject = mysql_fetch_array($r, MYSQL_NUM)){
									echo '<option value="'.$rowSubject[1].'"'.($rowSubject[0] == $row[8] ? ' selected' : '') .'>'.$rowSubject[1].'</option>';
								}
							}
					 
				print '</select>
	</div>
	<input type="hidden" name="id" value="' . $_GET['id'] . '" />
	<input type="submit" name="submit" class="button" value="Actualitza aquest fitxer!" />
	<input type="button" class="button" name="mainpage" value="Pàgina principal" onclick="location.href=\'index.php\'"/>
	</form>';
		}else { // Couldn't get the information.
		print '<p style="color: red;">No es poden obtenir les dades a causa de:<br />' . mysql_error($dbc) . '.</p><p>La consulta executada és: ' . $query . '</p>';
	}

} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) { // Handle the form.

	// Validate and secure the form data:
	$problem = FALSE;
	if (!empty($_POST['Name']) && !empty($_POST['ActDate']) && !empty($_POST['DateExp'])&& !empty($_POST['Pass'])&& !empty($_POST['Grade'])&& !empty($_POST['Subject'])) {
		$Name = mysql_real_escape_string(trim(strip_tags($_POST['Name'])), $dbc);
		$ActDate = mysql_real_escape_string(trim(strip_tags($_POST['ActDate'])), $dbc);
		$DateExp= mysql_real_escape_string(trim(strip_tags($_POST['DateExp'])), $dbc);
		$Pass= mysql_real_escape_string(trim(strip_tags($_POST['Pass'])), $dbc);
		$Grade= mysql_real_escape_string(trim(strip_tags($_POST['Grade'])), $dbc);
		$Subject= mysql_real_escape_string(trim(strip_tags($_POST['Subject'])), $dbc);
		if (HasLogged()){ $UserName= $_SESSION["logID"];} 
		
	} else {
		print '<p style="color: red;">Hi ha camps sense emplenar!.</p>';
		$problem = TRUE;
	}

	if (!$problem) {
		$gradeSelected ='SELECT * FROM Grade where Name= "'.$Grade.'"';  //Search what option is selected on the grade field
		if($r = mysql_query($gradeSelected,$dbc)) {
			while ($row = mysql_fetch_array($r, MYSQL_NUM)){
			$codeGrade=$row[0];
			}
		}
		$subjectSelected ='SELECT * FROM Subject WHERE Name="'.$Subject.'"';   //Search what option is selected on the subject field
		if($r = mysql_query($subjectSelected,$dbc)) {
			while ($row = mysql_fetch_array($r)){
				$codeSubject=$row[0];
			}
		}
		if (correctDate($ActDate, $DateExp)){ //After do the update, we want to control if dates entered are correct, in this case, we'll do the update otherwise date error will be shown
			// Define the query.
			$UpdateQuery = "UPDATE Files SET Name='$Name', ActivationDate='$ActDate', DateExpiry='$DateExp', Password='$Pass', CodeGrade='$codeGrade', CodeSubject='$codeSubject', UserName='$UserName' WHERE Code={$_POST['id']}";
			$r = mysql_query($UpdateQuery, $dbc); // Execute the query.
			// Report on the result:
			if (mysql_affected_rows($dbc) == 1) {
				print '<p>El fitxer ha estat actualitzat amb éxit.</p>';
				print '<input type="button" class="button" name="mainpage" value="Pàgina Principal" onclick="location.href=\'index.php\'"/>';
			} else {
				print '<p style="color: red;">No es poden obtenir les dades a causa de:<br />' . mysql_error($dbc) . '.</p><p>La consulta executada és: ' . $UpdateQuery . '</p>';
			}
		} else {
			echo "<p><em>Les dates introduïdes no pareixen ser correctes</em></p>";
			echo '<input type="button" class="button" name="uploads" value="Torna enrera" onclick="history.go(-1);return true;"/>';
		}
	} // No problem!

} else { // No ID set.
	print '<p style="color: red;">Ha ocorregut un error a la pàgina.</p>';
} // End of main IF.

mysql_close($dbc); // Close the connection.

?>
</div>
</body>
</html>